//
//  GroupedRequestsVC.swift
//  BWNetworkKit_Example
//
//  Created by zhuxuhong on 2022/3/21.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import BWUIKit
import BWToolKit
import BWNetworkKit
import BWHUDKit
import UIKit

class GroupedRequestsVC: TableViewController {
    override func didLoad() {
        super.didLoad()
        
        loadImages()
    }
    
    var images: [UIImage] = []
    
    let imageURLs: [URL] = {
        let prefix = "https://raw.githubusercontent.com/onevcat/Kingfisher-TestImages/master/DemoAppImage/HighResolution"
        return (1...20).map { URL(string: "\(prefix)/\($0).jpg")! }
    }()
    
    
    func reloadImages() {
        listAdapter.data = .init(registers: [
        ], sections: [
            .init(items: images.map{
                .init(reuseId: ImageCell.RID, height: 400, data: $0, cellConfigure: nil, action: nil)
            })
        ])
        tableView.scrollToRow(at: .init(row: images.count-1, section: 0), at: .bottom, animated: true)
    }
    
    var imageDownloadOperations: [GCD.Task.Operation] = []
    
    func loadImages()
    {
        let apis: [API.Image] = imageURLs.map{
            return .download(fullUrl: $0.absoluteString)
        }
        imageDownloadOperations =
        Networker.send(
            apis: apis,
            queuePolicy: .concurrent(maxCount: 3)
        ) { op in
            return .init {
                [weak self] state in
                   guard let self = self else {
                       return
                   }
                   switch state {
                   case .loading:
                       HUD.loading()
                   case .failed(let error):
                       HUD.dismissAll()
                       HUD.toast(error.localizedDescription)
                       op.completionBlock?()
                   case .success(let data):
                       guard let img = UIImage.init(data: data) else {
                           return
                       }
                       self.images.append(img)
                       self.reloadImages()
                       op.completionBlock?()
                   case .finished:
                       HUD.dismissAll()
                   }
            }

        } completion: { result in
            HUD.toast("\(result)")
        }
    }
    
    override func willDisapppear() {
        imageDownloadOperations.forEach{op in
            if !op.isFinished {
                op.cancel()
            }
        }
    }
}
